package com.traffic.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.traffic.annotation.Power;
import com.traffic.constant.Const;
import com.traffic.constant.Status;
import com.traffic.entity.About;
import com.traffic.exception.BaseException;
import com.traffic.mapper.AboutMapper;
import com.traffic.service.AboutService;
import com.traffic.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * Created by IntelliJ IDEA.
 * User: KingRainGrey
 * Date: 2020/9/9
 */
@Service
public class AboutServiceImpl extends ServiceImpl<AboutMapper, About> implements AboutService {
    @Autowired
    private AboutMapper aboutMapper;
    @Autowired
    private JwtUtil jwtUtil;

    /**
     * 添加一条新的about的后
     * 设置最新的为启用
     * 需要关闭当前启用的about
     * @param about
     * @return
     */
    @Transactional
    @Power(authority = Const.AUTH_TEXT)
    @Override
    public About add(About about) {
        if (jwtUtil.confirm(jwtUtil.getAccount(Const.TAG_ADMIN))) {
            QueryWrapper<About> wrapper = new QueryWrapper<>();
            wrapper.eq("status", Const.CONFIG_START);

            About old = aboutMapper.selectOne(wrapper);
            if (ObjectUtil.isNotNull(old)) {
                old.setStatus(Const.CONFIG_CLOSE);
                aboutMapper.updateById(old);
            }

            about.setStatus(Const.CONFIG_START);
            aboutMapper.insert(about);
            return about;
        }
        throw new BaseException(Status.COMMON_ERROR);
    }


    /**
     * 返回当前启用的about
     * @return
     */
    @Override
    public About get() {
        QueryWrapper<About> wrapper = new QueryWrapper<>();
        wrapper.eq("status", Const.CONFIG_START);
        About about = aboutMapper.selectOne(wrapper);
        return about;
    }
}
